package site.qianli.discover.service;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import site.qianli.discover.common.annotations.Info;
import site.qianli.discover.common.exception.user.UserAlreadyExistException;
import site.qianli.discover.common.util.UUIDUtils;
import site.qianli.discover.common.vo.Article;
import site.qianli.discover.common.vo.User;
import site.qianli.discover.common.vo.UserExample;
import site.qianli.discover.dao.UserMapper;

@Component
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ArticleService articleService;

	public String insert(User user) {
		if (user.getId() == null) {
			user.setId(UUIDUtils.getID32());
		}

		UserExample example = new UserExample();
		// example.createCriteria().andAccountEqualTo(user.getAccount()).andPhoneEqualTo(user.getPhone());

		example.or().andAccountEqualTo(user.getAccount()).andPhoneEqualTo(user.getPhone());
		example.or().andPhoneEqualTo(user.getPhone());
		// example.or().andAccountOrPhoneEqualTo(user.getAccount());

		List<User> userList = userMapper.selectByExample(example);

		if (CollectionUtils.isNotEmpty(userList)) {
			throw new UserAlreadyExistException();
		}
		user.setDateCreate(System.currentTimeMillis());
		userMapper.insert(user);
		return user.getId();
	}

	@Info
	public User selectByPrimaryKey(String id) {
		return userMapper.selectByPrimaryKey(id);
	}

	public User selectByAccount(String account) {
		if (StringUtils.isEmpty(account)) {
			return null;
		}
		UserExample example = new UserExample();
		List<User> userList = userMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(userList)) {
			return null;
		} else {
			return userList.get(0);
		}
	}

	public List<User> selectAll() {
		UserExample example = new UserExample();
		return userMapper.selectByExample(example);

	}

	/**
	 * 事物，要么都成功，要么都不成功
	 * 
	 * @param user
	 * @param article
	 * @return
	 */
	@Transactional
	public boolean insertUserAndArtical(User user, Article article) {
		articleService.insert(article);
		userMapper.insert(user);
		return true;
	}
}
